import React, { useEffect, useState } from 'react';
import { Affix, Button, Alert, Radio, Select, Input, Space, Row, Col, Table, Popover, message } from 'antd';
import request, { exportFile } from '@/utils/request';
import { CmdbContent, CmdbHeader, isAuthorized, HcpTableTooltip, Authorized } from '@/components';
import moment from 'moment';
import permission from '@/config/permission';
import cmdbres from '@/data/cmdbres';
import DeleteModal from './delete';
import CreateModal from './create';
import DetailModal from './detail';

const ModelUnique = ({ history, moduleId, moduleCode }) => {
    const isHiddden = moduleCode == 'biz' ? true : false;
    console.log('moduleCode123', moduleCode);
    const [searchValue, setSearchValue] = useState();
    const [loading, setLoading] = useState(false);
    const [tableData, setTableData] = useState([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const [row, setRow] = useState({});
    const [showCreateModal, setShowCreateModal] = useState(false);
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [showDetailModal, setShowDetailModal] = useState(false);
    const [filelds, setFilelds] = useState({});
    const getTableData = async (params = { current: 1, pageSize: 10 }) => {
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.queryPropertyUnique(moduleId),
                params: {
                    pageSize: params.pageSize,
                    pageNumber: params.current,
                },
            });
            setLoading(false);
            if (res && res.data) {
                setPagination((pagination) => ({
                    ...pagination,
                    current: res.pageNumber,
                    pageSize: res.pageSize,
                    total: res.total,
                }));
                res.data.map((item, index) => (item.key = index));
                setTableData(res.data);
            } else {
                setTableData([]);
            }
        } catch (error) {
            console.log(error);
        }
    };

    const queryModelFilelds = async () => {
        try {
            let res = await request({
                ...cmdbres.queryModelPropertyList,
                data: {
                    queryFilter: {
                        EQ: {
                            cmModuleId: moduleId,
                        },
                    },
                },
            });
            if (res && res.code == 200) {
                let obj = {};
                res.data.map((item) => {
                    obj[item.id] = item;
                });
                setFilelds(obj);
            } else {
                setFilelds({});
            }
        } catch (error) {
            setFilelds({});
            console.log(error);
        }
    };

    useEffect(() => {
        if (moduleId) {
            queryModelFilelds();
            getTableData();
        }
    }, [moduleId]);

    const handleTableChange = (e) => {
        getTableData(e);
    };

    const columnsData = [
        {
            title: '校验规则',
            key: 'name',
            dataIndex: 'name',
            isShow: true,
            width: 140,
            copyable: true,
            ellipsis: true,
            render: (text, record, index) => {
                const keys = record.keys;
                let str = '';
                if (Object.keys(filelds).length) {
                    keys.map((item, index) => {
                        str += filelds[item.keyId]?.propertyName ?? item.keyId;
                        if (index < keys.length - 1) {
                            str += '+';
                        }
                    });
                } else {
                    str = '-';
                }

                return <span title={str}>{str}</span>;
            },
        },
        {
            title: '唯一主键',
            dataIndex: 'mustCheck',
            isShow: true,
            width: 140,
            ellipsis: true,
            render: (text, record, index) => (text ? '是' : '否'),
        },

        // {
        //     title: "操作",
        //     width: 100,
        //     render: (text, record, index) => {
        //         return (
        //         <Space key={record.id}>
        //             <Popover content="编辑">
        //                 <span
        //                     // disabled={record.mustCheck}
        //                     className="iconfont icon-edit"
        //                     onClick={() => {
        //                         setRow(record);
        //                         setShowCreateModal(true);
        //                     }}
        //                 />
        //             </Popover>
        //             <Popover content="删除">
        //                 <span
        //                     disabled={record.mustCheck}
        //                     className="iconfont icon-delete"
        //                     onClick={() => {
        //                         if(tableData.length == 1) {
        //                             message.warning("模型至少需要有一组的必填唯一校验项");
        //                             return;
        //                         }
        //                         if(!record.mustCheck) {
        //                             setRow(record);
        //                             setShowDeleteModal(true); }}
        //                         }
        //                 />
        //             </Popover>
        //         </Space>
        //         )
        //     }
        // }
    ];

    let columns = columnsData;
    if (!isHiddden) {
        columns.push({
            title: '操作',
            width: 100,
            render: (text, record, index) => {
                return (
                    <Space key={record.id}>
                        <Authorized authority={permission.modelUniVerify_edit} noMatch={null}>
                            <Popover content="编辑">
                                <span
                                    // disabled={record.mustCheck}
                                    className="iconfont icon-edit"
                                    onClick={() => {
                                        setRow(record);
                                        setShowCreateModal(true);
                                    }}
                                />
                            </Popover>
                        </Authorized>
                        <Authorized authority={permission.modelUniVerify_delete} noMatch={null}>
                            <Popover content="删除">
                                <span
                                    disabled={record.mustCheck}
                                    className="iconfont icon-delete"
                                    onClick={() => {
                                        if (tableData.length == 1) {
                                            message.warning('模型至少需要有一组的必填唯一校验项');
                                            return;
                                        }
                                        if (!record.mustCheck) {
                                            setRow(record);
                                            setShowDeleteModal(true);
                                        }
                                    }}
                                />
                            </Popover>
                        </Authorized>
                    </Space>
                );
            },
        });
    }

    return (
        <div style={{ backgroundColor: '#fff', padding: '0 20px' }}>
            {isHiddden ? null : (
                <div style={{ display: 'inline-block', width: '50%' }}>
                    <Space className="m-b-10">
                        <Authorized authority={permission.modelUniVerify_add} noMatch={null}>
                            <Button
                                className="hcp_toolbar_btn"
                                type="primary"
                                onClick={() => {
                                    setRow({});
                                    setShowCreateModal(true);
                                }}
                            >
                                新建校验
                            </Button>
                        </Authorized>
                    </Space>
                </div>
            )}
            <Table
                columns={columns}
                loading={loading}
                dataSource={tableData}
                scroll={{ x: '100%' }}
                pagination={{
                    showSizeChanger: true,
                    // showTotal: (total, range) => (
                    //     <span
                    //         style={{
                    //             position: 'absolute',
                    //             left: '0%',
                    //             fontSize: '13px',
                    //             color: 'gray',
                    //         }}
                    //     >
                    //         共 {total} 条记录
                    //     </span>
                    // ),
                    showQuickJumper: {
                        goButton: <Button style={{ margin: '0 10px' }}>确定</Button>,
                    },
                    ...pagination,
                }}
                onChange={handleTableChange}
                hideSetting
            />
            {showCreateModal && (
                <CreateModal
                    visible={showCreateModal}
                    setVisible={setShowCreateModal}
                    onCreateFinish={getTableData}
                    info={row}
                    moduleId={moduleId}
                />
            )}
            <DeleteModal
                onDeleteFinish={getTableData}
                visible={showDeleteModal}
                setVisible={setShowDeleteModal}
                info={row}
            />
            <DetailModal visible={showDetailModal} setVisible={setShowDetailModal} info={row} />
        </div>
    );
};

export default ModelUnique;
